<?php

class Vlib_Models_Table extends Zend_Db_Table {
    
    const TABLE_MODULE = "module";
    const TABLE_PRODUCT = "product";
    const TABLE_PRODUCT_CATEGORY = "product_category";
    const TABLE_ATTACHMENT = "attachment";
    protected $_logger = null;
    
    public function __construct($config = array(), $definition = null) {
        parent::__construct($config, $definition);
        // initialize logger instance
        $this->_logger = Vlib_Logger::getInstance();
        
    }
    
    public function setName($tableName) {
        $this->_name = $this->__($tableName);
    }
    
    public function __($tableName) {
        if (!$tableName) return;
        $appConf = Vlib_Config::getConfig();
        $env = APPLICATION_ENV;
        $tablePrefix = $appConf[$env]['resources']['db']['params']['prefix'];
        return $tablePrefix . $tableName;
    }
    
    public function getModulesByUser() {
        $this->_logger->debugIn();
        
        try {
            $moduleLogic = new self();
            $moduleLogic->setName(self::TABLE_MODULE);
            
            // crate select statement
            $select = $moduleLogic->_db->select()
                    ->distinct()
                    ->from(array('m' => $this->__(self::TABLE_MODULE)))
                    ->where('m.module_i_del_flg = ?', 0);

            $select->order('m.module_i_order ASC');

            $this->_logger->sql($select->__toString());
            
            // fetch data
            $arrResult = $this->_db->fetchAll($select);

            $this->_logger->debugOut();

            return $arrResult;
        } catch (Zend_Db_Exception $e) {
            $this->_logger->error($e->getMessage());
        }
        
        $this->_logger->debugOut();
        return array();
    }
    
    public function getProduct($aryCondition) {
        $this->_logger->debugIn();
        
        try {
            $moduleLogic = new self();
            $moduleLogic->setName(self::TABLE_PRODUCT);
            
            // crate select statement
            $select = $moduleLogic->_db->select()
                    ->from($this->__(self::TABLE_PRODUCT_CATEGORY),array('product_category_id','product_category_name'))
                    ->where('product_category_delete_flag = ?', 0)
                    ->joinLeft($this->__(self::TABLE_PRODUCT),"product_category_id = product_cate_id and product_delete_flag = 0" ,array('product_id','product_cate_id','product_name'));
            if(is_array($aryCondition)) {
                foreach($aryCondition as $key=>$val) :
                    $select->where("$key = ?", $val);
                endforeach;
            }
            $select->order('product_category_order');
            $select->order('product_order');
            $this->_logger->sql($select->__toString());
            
            // fetch data
            $arrResult = $this->_db->fetchAll($select);
            $this->_logger->debugOut();

            return $arrResult;
        } catch (Zend_Db_Exception $e) {
            $this->_logger->error($e->getMessage());
        }
        
        $this->_logger->debugOut();
        return array();
    }
    
    
    public function getFirstModuleName() {
        $this->_logger->debugIn();
        
        $modules = $this->getModulesByUser();
        if ($modules) {
            $module = $modules[key($modules)];
        }
        
        $this->_logger->debugOut();
        
        return $module;
    }
    
    public function getDbConfig($_module = '') {
        $this->_logger->debugIn();
        
        if (!$_module) {
            $this->_logger->debugOut();
            return array();
        }
        
        
        
        $this->_logger->debugOut();
    }

/*-------------------------------------------- Start attachment model --------------------------------------------- */    
    /**
     *  @desc Get file attachment informations
     *
     *  @author Tran Nghia <nghiat@vnext.vn>
     *  @since 2012/02/29
    */
    public function findAttachment($aryCondition, &$output) {
        $this->_logger->debugIn();
        try {
            $intIsOk = Vlib_Constant::VLIB_OK;
            $aryFieldSelect = array(
                                    'attachment_id',
                                    'attachment_type',
                                    'attachment_issue_code',
                                    'attachment_relation_id',
                                    'attachment_filename',
                                    'attachment_hash_name',
                                    'attachment_file_type',
                                    'attachment_mime_type',
                                    'attachment_file_size',
                                    'attachment_order' 
                                );                

            $selectStatement = $this->_db->select()
                                        ->from($this->__(self::TABLE_ATTACHMENT), $aryFieldSelect)
                                        ->where(' attachment_id  = ? ', $aryCondition['attachment_id']);
            $this->_logger->sql($selectStatement->__toString());
            $output = $this->_db->fetchAll($selectStatement);
        }catch(Zend_Db_Exception $e){
            $this->_logger->error($e->getMessage(),VLIB_SELECT);
            $intIsOk = Vlib_Constant::VLIB_ERR_DB_EXCEPTION;
        }            
        $this->_logger->debugOut();
        return $intIsOk;
    }

    /**
     * @desc insert file attachment
     * 
     * @author Tran Nghia <nghiat@vnext.vn>
     * @since 2012/02/29
     */
    public function insertFileAttachmentList($listFile, $aryBeanMerge, &$newId = null) {
        $this->_logger->debugIn();
        try {
            $intIsOk = Vlib_Constant::VLIB_ERR_EX_OTHER;
            $intPK = '';
            $n = count($listFile);
            for ($i = 0; $i < $n; $i++) {
                $row = array();
                $row = array_merge($listFile[$i], $aryBeanMerge);
                 $intPK = $this->_db->insert($this->__(self::TABLE_ATTACHMENT), $row);
                 $newId = $this->_db->lastInsertId();
            }
            $intIsOk =  ($intPK) ? Vlib_Constant::VLIB_OK : Vlib_Constant::VLIB_ERR_EX_OTHER;
        }catch(Zend_Db_Exception $e){
            $this->_logger->error($e->getMessage(),VLIB_INSERT);
            $intIsOk = Vlib_Constant::VLIB_ERR_DB_EXCEPTION;
        }
        $this->_logger->debugOut();
        
        return $intIsOk;
    }

    /**
     * @desc removed file attach
     * 
     * @author Tran Nghia <nghiat@vnext.vn>
     * @since 2012/02/29
     */
    public function deleteFile($deleteId) {
        $this->_logger->debugIn();
        $intIsOk = Vlib_Constant::VLIB_ERR_EX_OTHER;
        $aryBin = array();
        
        try {
            
            $aryParam = array('attachment_delete_flag' => 1);
            //$aryWhere = array('attachment_id' => $deleteId );
            $where = ' attachment_id = '.(int) $deleteId;
            $intIsOk = $this->_db->update($this->__(self::TABLE_ATTACHMENT), $aryParam, $where);
            
        } catch (Zend_Db_Exception $e) {
            $this->_logger->error($e->getMessage(),VLIB_DELETE);
            $intIsOk = Vlib_Constant::VLIB_ERR_DB_EXCEPTION;
        }
        $this->_logger->debugOut();
        
        return $intIsOk;
    }
    
    /**
     * @desc Cập nhật tệp đính kèm
     * @param $aryCondition điều kiện & dữ liệu để cập nhật
     * @author vinhnv@vnext.vn
     * @since 2012/03/27
    */
    public function updateAttachment($aryCondition){
        $this->_logger->debugIn(); // vào hàm
        
        // Khởi tạo biến
        $intIsOk = Vlib_Constant::VLIB_OK;
        try{
            $where = ' attachment_id = ' . (int) $aryCondition['attachment_id'];
            $intIsOk = $this->_db->update($this->__(self::TABLE_ATTACHMENT), $aryCondition, $where);
        }catch(Zend_Db_Exception $e){
            $intIsOk = Vlib_Constant::VLIB_ERR_DB_EXCEPTION;
            $this->_logger->error($e->getMessage(), VLIB_UPDATE);
        }

        $this->_logger->debugOut(); // ra hàm
        
        // Trả lại
        return $intIsOk;
    }
    
    /**
     * @desc get list file attachment
     * 
     * @author Tran Nghia <nghiat@vnext.vn>
     * @since 2012/02/29
     */
    public function getFileAttachment(&$aryFileAttachment, $attachment_type, $attachment_issue_code = null, $attachment_relation_id = null, $attachment_id = null){
        $this->_logger->debugIn();
        $intIsOk = Vlib_Constant::VLIB_ERR_EX_OTHER;
        try {
            
            $where = '';
            $aryBin = array();
            $aryFieldSelect = array(
                                'attachment_id',
                                'attachment_type',
                                'attachment_issue_code',
                                'attachment_filename',
                                'attachment_file_type',
                                'attachment_file_size',
                                'attachment_mime_type',
                                'attachment_hash_name'
                            );
            $objSql = $this->_db->select()->from($this->__(self::TABLE_ATTACHMENT), $aryFieldSelect);
            
            $sql = $objSql->where('attachment_delete_flag = ? ', 0);
            
            if(isset($attachment_type) && $attachment_type != ''){
                $sql = $objSql->where('attachment_type = ? ',$attachment_type);
            }    
            if(isset($attachment_issue_code) && $attachment_issue_code != ''){
                $sql = $objSql->where('attachment_issue_code = ? ',$attachment_issue_code);
            }
            if(isset($attachment_relation_id) && $attachment_relation_id != ''){
                $sql = $objSql->where('attachment_relation_id = ? ',$attachment_relation_id);
            }
            if(isset($attachment_id) && $attachment_id != ''){
                $sql = $objSql->where('attachment_id = ? ',$attachment_id);
            }
            $this->_logger->sql($sql->__toString());
            $aryFileAttachment = $this->_db->fetchAll($sql);

            if($aryFileAttachment !== false) {
                $intIsOk = Vlib_Constant::VLIB_OK;
            }

        } catch (Zend_Db_Exception $e) {
             $this->_logger->error($e->getMessage(),VLIB_SELECT);
             $intIsOk = Vlib_Constant::VLIB_ERR_DB_EXCEPTION;
        }
        // End Log
        $this->_logger->debugOut();
        return $intIsOk;
    }
/*----------------------------------------------------- End attachment model ---------------------------------------------- */        

}